package com.matrix.draft.sockettest.protocoltcp.handler;

import com.matrix.draft.sockettest.protocoltcp.pojo.ProtocolMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.stream.IntStream;

public class ClientHandler extends SimpleChannelInboundHandler<ProtocolMessage> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送5个ProtocolMessage对象
        IntStream.range(0, 5).forEach(i -> {
            byte[] bytes = ("你好TCP粘包拆包解决方案" + i).getBytes(StandardCharsets.UTF_8);
            ctx.writeAndFlush(new ProtocolMessage().setLen(bytes.length).setContent(bytes));
        });
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage msg) throws Exception {
        // 读取
        System.out.println("Got from server : " + new String(msg.getContent(), StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
